<template>
<el-card>
  <h1 style="color: orange">{{c.id==null?'发布':'修改'}}内容页面</h1>
  <el-form label-width="80px">
    <el-form-item label="文章标题">
      <el-input placeholder="请输入文章标题" v-model="c.title"></el-input>
    </el-form-item>
    <el-form-item label="文章分类">
      <!--input事件是输入数据,数据触发时,双向绑定的值还未发生改变
          change事件是值改变,事件触发时,双向绑定的值已经发生改变
      -->
      <el-radio-group v-model="c.type" @change="handleChange">
        <el-radio-button label="1">食谱</el-radio-button>
        <el-radio-button label="2">视频</el-radio-button>
        <el-radio-button label="3">资讯</el-radio-button>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="二级分类">
        <el-select v-model="c.categoryId" placeholder="请选择">
          <!-- label是给用户看的内容,  value是选中之后得到的值-->
          <el-option v-for="cat in categoryArr"
                     :label="cat.name" :value="cat.id">
          </el-option>
        </el-select>
    </el-form-item>
    <el-form-item label="封面">
      <!--  上传组件开始      -->
      <el-upload
          v-model:file-list="fileList"
          action="http://localhost:8080/v1/upload"
          name="file"
          limit="1"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :on-success="handleSuccess"
      >
        <el-icon><Plus /></el-icon>
      </el-upload>

      <el-dialog v-model="dialogVisible">
        <img w-full :src="dialogImageUrl" alt="Preview Image" />
      </el-dialog>
      <!--  上传组件结束      -->
    </el-form-item>
    <el-form-item v-show="c.type==2" label="视频">
      <!--  上传组件开始      -->
      <el-upload
          action="http://localhost:8080/v1/upload"
          name="file"
          limit="1"
          accept="video/*"
          :on-remove="handleRemove"
          :on-success="handleSuccess"
      >
        <el-button>点击上传视频</el-button>
        <div>只能上传mp4文件,并且不能超过100MB</div>
      </el-upload>

      <el-dialog v-model="dialogVisible">
        <img w-full :src="dialogImageUrl" alt="Preview Image" />
      </el-dialog>
      <!--  上传组件结束      -->
    </el-form-item>
    <el-form-item v-show="c.type!=2" label="文章内容">
<!-- 装富文本编辑器元素     -->
      <div ref="editorContent"></div>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="postContent()">{{c.id==null?'发布':'修改'}}内容</el-button>
    </el-form-item>
  </el-form>
</el-card>
</template>

<script setup>
import {onMounted, ref} from "vue";
//导入富文本编辑器
import Editor from 'wangeditor';
import axios from "axios";
import router from "@/router";
import qs from "qs";

const categoryArr = ref([]);

//和页面元素绑定的内容对象
const c = ref({title: "", type: "1", categoryId: ""})

const handleChange=()=>{
  c.value.categoryId=""; //把记录的二级分类id清空,因为此时一级分类已经发生改变
  loadCategories();
}
const loadCategories=()=>{
  //请求食谱下的二级分类
  axios.get('http://localhost:8080/v1/categories/'+c.value.type+'/sub')
      .then((response)=>{
        if (response.data.code==1){
          categoryArr.value = response.data.data;
        }
      })
}
//得到页面中用来装编辑器的div
const editorContent = ref(null);
let editor = null;
//在Vue实例挂载完成时初始化富文本编辑器
onMounted(()=>{
  //请求食谱下的二级分类
  loadCategories()

  //创建富文本编辑器的实例
  editor = new Editor(editorContent.value);
  //设置占位文本
  editor.config.placeholder="请输入内容详情...";
  //将富文本编辑器渲染到页面中
  editor.create();

  //判断是否包含id
  if (location.search.includes('id')){
    let id = new URLSearchParams(location.search).get('id');
    //通过id请求内容详情数据
    axios.get('http://localhost:8080/v1/contents/'+id+"/update")
        .then((response)=>{
          if (response.data.code==1){
            c.value = response.data.data;
            fileList.value.push({url: 'http://localhost:8080' + c.value.imgUrl})
            //查询请求二级分类
            loadCategories();
            //把内容显示到富文本编辑器里面
            editor.txt.html(c.value.content);
          }
        })
  }
})

/*************上传相关开始******************/
const fileList = ref([])

const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const handleSuccess = (response,uploadFile,uploadFiles)=>{
  //判断上传的是图片还是视频
  if (uploadFile.raw.type.includes('image')){//图片
    //把上传成功的图片路径保存到c对象中, 点击发布时提交给服务器
    c.value.imgUrl = response.data;
  }else{//视频
    c.value.videoUrl = response.data;
  }

}
const handleRemove = (uploadFile, uploadFiles) => {
  //发出删除请求
  let url;
  if (uploadFile.response) {
    url = uploadFile.response.data;
    if (uploadFile.raw.type.includes('image')){
      c.value.imgUrl = null; // 把删除文件的路径 清空
    }else{//视频
      c.value.videoUrl = null;
    }
  } else {
    url = uploadFile.url;
  }
  axios.post('http://localhost:8080/v1/remove?url=' + url)
      .then((response) => {
        if (response.data.code == 1) {
          console.log("服务器图片删除完成!");
        }
      });
}

const handlePictureCardPreview = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url
  dialogVisible.value = true
}
/*************上传相关结束******************/

const postContent = ()=>{
  if (c.value.imgUrl==null){alert("请选择封面!");return;}
  if (c.value.title.trim()==''){alert('标题不能为空!');return;}
  if (c.value.type!=2){//食谱和资讯
    //把富文本编辑器里面的内容取出  获取富文本编辑器中的标签内容
    c.value.content = editor.txt.html();
    //设置文章摘要   从纯文本内容中截取前30个字符作为文章的摘要
    c.value.brief = editor.txt.text().slice(0,30);
  }else{//视频
    if (c.value.videoUrl==null){alert('请选择上传的视频文件!');return;}
  }

  //设置作者id为当前登录的用户id
  let user = localStorage.user?JSON.parse(localStorage.user):null;
  if (user==null){
    alert("请先登录!");
    router.push('/login');
    return;
  }
  c.value.createBy = user.id;
  //发请求
  let data = qs.stringify(c.value);
  axios.post('http://localhost:8080/v1/contents/add-new',data)
      .then((response)=>{
        if (response.data.code==1){
          //判断是从哪个页面来的修改页面
          if (localStorage.editFrom=='admin'){//来自后台管理页面
            router.push('/admin/content');
            localStorage.editFrom=null;//把记录的来自后台的管理页面的标识清理
          }else {
            router.push('/personal/management');//跳转到稿件管理页面
          }
        }
      })

}

</script>

<style scoped>

</style>